<template>
  <div class="app-main-container">
    <div class="app-main-title">
      {{ title }}
      <div class="goback" @click="$router.replace(`/options/homePageList`)">
        <i class="el-icon-refresh-left" /> 返回上一页
      </div>
    </div>
    <el-form
      ref="ruleForm"
      class="doumee-form"
      :model="param"
      :rules="rules"
      label-width="100px"
      label-suffix="："
    >
      <el-form-item label="广告类型" prop="title">
        <el-select
          v-model="param.type"
          clearable
          style="width: 400px"
          placeholder="请选择广告类型"
          @change="deleteDeviceConfigAddImage"
        >
          <el-option
            v-for="item in adTypes"
            :key="item.id"
            :label="item.name"
            :value="item.id"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="广告标题" prop="title">
        <el-input
          v-model="param.title"
          type="text"
          style="width: 400px"
          placeholder="请输入标题"
          maxlength="20"
        />
      </el-form-item>
      <el-form-item label="宣传图" prop="imageFullPath">
        <transition name="fade">
          <Cropper
            v-if="dialogCropperVisible"
            :option-img="optionImg"
            :fileinfo="fileinfo"
            use-type="KNOWLEDGE_IMG"
            :fixed-number="shopId == 106?[644, 419]:[690,300]"
            @formSubmit="cropperSubmit"
            @formClose="cropperClose"
          />
        </transition>
        <div class="flex-c">
          <el-upload
            class="device-uploader"
            :action="uploadFileUrl"
            accept=".jpg,.png"
            :data="uploadData"
            :show-file-list="false"
            :on-change="addFileChange"
            :on-success="uploadSuccess"
            :auto-upload="true"
          >
            <i class="el-icon-plus uploader-icon" />
            <div
              v-show="param.imageFullPath"
              class="file"
              :style="'background-image: url(' + param.imageFullPath + ')'"
            >
              <div class="delete">
                <i
                  class="el-icon-delete icon"
                  @click.stop="deleteDeviceConfigAddImage"
                />
              </div>
            </div>
          </el-upload>
          <span class="tip-style">
            支持上传一张1M大小,jpg、png格式图片
            <span v-if="param.type !== '1'">,建议图片尺寸{{ shopId == 106?'644px X 419px':'690px X 300px ' }}</span>
          </span>
        </div>
      </el-form-item>
      <el-form-item label="关联类型" prop="configId">
        <el-select
          v-model="param.configId"
          style="width: 400px"
          placeholder="请选择关联类型"
          @change="selectType"
        >
          <el-option
            v-for="item in types"
            :key="item.id"
            :label="item.typeName"
            :value="item.id"
          />
        </el-select>
      </el-form-item>
      <!-- <el-form-item v-if="param.configId&&param.configId!=5" label="适用场馆" prop="venueId">
        <el-select
          v-model="param.venueId"
          clearable
          style="width: 400px"
          placeholder="请选择适用场馆"
          @change="selectVenue"
        >
          <el-option
            v-for="item in venueList"
            :key="item.id"
            :label="item.name"
            :value="item.id"
          />
        </el-select>
      </el-form-item> -->
      <el-form-item v-if="param.configId&&param.configId==5" label="适用场馆">
        <el-select
          v-model="param.venueIds"
          multiple
          clearable
          style="width: 400px"
          placeholder="请选择适用场馆"
          @change="selectVenue"
        >
          <el-option
            v-for="item in venueList"
            :key="item.id"
            :label="item.name"
            :value="item.id"
          />
        </el-select>
      </el-form-item>
      <el-form-item v-if="param.configId&&param.configId!=5" label="适用场馆" prop="venueIds">
        <el-select
          v-model="param.venueIds"
          :multiple-limit="1"
          multiple
          clearable
          style="width: 400px"
          placeholder="请选择适用场馆"
          @change="selectVenue"
        >
          <el-option
            v-for="item in venueList"
            :key="item.id"
            :label="item.name"
            :value="item.id"
          />
        </el-select>
      </el-form-item>
      <el-form-item v-if="param.configId&&param.configId!=5&&param.venueIds.length == 1" label="关联内容" prop="aboutIndex">
        <el-select
          v-model="param.aboutIndex"
          style="width: 400px"
          placeholder="请选择关联内容"
          @change="selectContent"
        >
          <el-option
            v-for="(item, index) in activeList"
            :key="index"
            :label="item[activeName]"
            :value="index"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="排序码" prop="sort">
        <el-input
          v-model="param.sort"
          style="width: 400px"
          type="number"
          placeholder="请输入排序码"
          maxlength="20"
        />
      </el-form-item>
      <div class="line-style" />
      <el-form-item>
        <el-button
          v-preventReClick
          :loading="subLoading"
          type="primary"
          @click="onSubmit()"
        >提交</el-button>
      </el-form-item></el-form>
  </div>
</template>

<script>
import request from '@/utils/request'
import { uploadFile, bannerSave, bannerUpdate, bannerDetail, venueList, bannerConfigInfo } from '@/api'
import Cropper from '@/components/cropper'
export default {
  name: 'HomePageEdit',
  components: {
    Cropper
  },
  data() {
    return {
      subLoading: false,
      shopId: sessionStorage.getItem('shopId'),
      uploadFileUrl: uploadFile,
      optionImg: '',
      fileinfo: {},
      dialogCropperVisible: false,
      uploadData: {
        folder: 'KNOWLEDGE_IMG',
        type: ''
      },
      venueList: [],
      title: '',
      adTypes: [
        // 0:首页banner，1:新人广告; 广告类型 ,
        { id: '0', name: '首页banner' },
        { id: '1', name: '新人广告' }
      ],
      queryPath: '',
      param: { venueIds: [] },
      types: [],
      activeList: [],
      rules: {
        imageFullPath: [
          { required: true, message: '请上传列表图', trigger: 'change' }
        ],
        title: [
          { required: true, message: '请输入标题', trigger: 'blur' }
        ],
        info: [
          { required: true, message: '请输入内容', trigger: 'blur' }
        ],
        sort: [
          { pattern: /^\+?[1-9][0-9]*$/, message: '请输入排序码', trigger: 'blur' }
        ],
        venueIds: [
          { required: true, message: '请选择适用场馆', trigger: 'change' }
        ],
        configId: [
          { required: true, message: '请选择关联类型', trigger: 'change' }
        ]
        // aboutIndex: [
        //   { required: true, message: '请选择关联内容', trigger: 'change' }
        // ]
      },
      edit: false,
      cgList: [],
      id: ''
    }
  },
  mounted() {
    if (this.$route.query.id) {
      this.$route.meta.title = '编辑首页广告'
      this.title = '编辑首页广告'
      this.id = this.$route.query.id
      this.edit = true
      this.getData()
    } else {
      this.$route.meta.title = '新增首页广告'
      this.title = '新增首页广告'
      this.getConfigInfo()
    }
    venueList({
      param: {}
    })
      .then((res) => {
        if (res.errorCode !== '000000') return
        this.venueList = res.recordList
      })
      .catch(() => {})
  },
  methods: {
    getData() {
      bannerDetail({ param: { id: this.id }}).then(res => {
        if (res.errorCode === '000000') {
          this.param = res.record
          sessionStorage.setItem('venueId', res.record.venueIds[0])
          bannerConfigInfo({ param: {}}).then(resb => {
            if (resb.errorCode === '000000') {
              this.types = resb.record
              this.types.forEach(item => {
                if (item.id === this.param.configId) {
                  this.activeName = item.nameKey
                  this.queryPath = item.queryPath
                  this.param.idKey = item.idKey
                  this.activeName = item.nameKey
                  this.param.jumpPath = item.jumpPath
                  if (item.jumpPath) {
                    this.getActive()
                  }
                }
              })
            }
          }).catch(err => {
            console.log(err)
          })
        }
      }).catch(err => {
        console.log(err)
      })
    },
    getConfigInfo() {
      bannerConfigInfo({}).then(res => {
        if (res.errorCode === '000000') {
          this.types = res.record
        }
      }).catch(err => {
        console.log(err)
      })
    },
    selectVenue(v) {
      this.activeList = []
      this.param.paramValue = ''
      this.param.paramName = ''
      this.$set(this.param, 'aboutIndex', '')
      sessionStorage.setItem('venueId', v)
      if (this.param.jumpPath && this.param.venueIds.length === 1) {
        this.getActive()
      }
    },
    selectType(id) {
      this.activeList = []
      this.param.paramValue = ''
      this.param.paramName = ''
      this.$set(this.param, 'venueIds', [])
      const item = this.types.find(item => item.id === id)
      this.activeName = item.nameKey
      this.param.idKey = item.idKey
      this.param.jumpPath = item.jumpPath
      this.queryPath = item.queryPath
      this.$refs.ruleForm.clearValidate()
      // if (!this.param.venueId) {
      //   this.$message.error('请先选择场馆')
      //   return
      // }
      if (item.jumpPath && this.param.venueIds.length === 1) {
        this.getActive()
      }
    },
    getActive() {
      request({
        url: `/do?c=${this.queryPath}`,
        method: 'POST',
        data: { param: {
          venueId: this.param.venueIds[0],
          stadiumId: this.param.venueIds[0],
          courseStatus: '2',
          status: '1',
          flag: this.param.configId === 6 ? '2' : '1',
          saleStatus: '1'
        }}
      })
        .then(res => {
          if (res.errorCode === '000000') {
            this.activeList = res.recordList
            if (this.queryPath === '411006') {
              const now = +new Date().getTime()
              this.activeList = res.recordList.filter((item) => {
                const end = +new Date(item.saleDateEnd).getTime()
                return end > now
              })
            }
            this.activeList.forEach((item, index) => {
              if (item[this.param.idKey] === this.param.paramValue) {
                // this.param.aboutIndex = index
                this.$set(this.param, 'aboutIndex', index)
              }
            })
          }
        })
        .catch(err => {
          console.log(err)
        })
    },
    selectContent(index) {
      // console.log(index);
      const item = this.activeList[index]
      // console.log(item);
      this.param.paramValue = item[this.param.idKey]
      this.param.paramName = item[this.activeName] ?? item.name
    },
    // 上传图片成功
    uploadSuccess(res, file, fileList) {
      if (this.param.type !== '1') return
      if (res.success) {
        this.$set(this.param, 'imageFullPath', res.showUrl)
        this.$set(this.param, 'pathUrl', res.insertUrl)
        this.$refs.ruleForm.clearValidate()
      } else {
        this.$message.error(res.msg || '上传失败')
      }
    },
    // 裁剪确定按钮
    cropperSubmit(config) {
      // preImg 完整路径  urlPre 不包含域名
      if (config.success) {
        this.$set(this.param, 'imageFullPath', config.showUrl)
        this.$set(this.param, 'pathUrl', config.insertUrl)
        this.$refs.ruleForm.clearValidate()
        this.dialogCropperVisible = false
      } else {
        this.$message.error(config.msg || '上传失败')
        this.$refs.form.clearValidate()
        this.dialogCropperVisible = false
      }
    },
    // 裁剪取消
    cropperClose() {
      this.dialogCropperVisible = false
    },
    async addFileChange(file, fileList) {
      // 上传，拿到file文件
      // this.files = file.raw;
      if (this.param.type === '1') return
      this.$nextTick(() => {
        this.optionImg = URL.createObjectURL(file.raw)
        this.fileinfo = file.raw
        this.dialogCropperVisible = true
      })
    },
    // 删除已上传图片
    deleteDeviceConfigAddImage() {
      // this.$set(this.param, 'img2', '')
      this.$set(this.param, 'pathUrl', '')
      this.$set(this.param, 'imageFullPath', '')
    },
    onSubmit() {
      this.$refs.ruleForm.validate((valid) => {
        if (valid) {
          const param = { ...this.param }
          // if (param.configId !== 5) {
          //   param.venueIds = [param.venueId]
          // }
          if (param.configId !== 5 && param.venueIds.length === 0) {
            this.$message.error('请先选择场馆')
            return
          }
          this.subLoading = true
          if (this.edit) {
            bannerUpdate({
              param
            }).then(res => {
              this.subLoading = false
              if (res.errorCode === '000000') {
                this.$message.success('提交成功')
                this.$router.replace(`/options/homePageList?renovate=1`)
              }
            }).catch(err => {
              console.log(err)
            })
          } else {
            param.status = '1'
            bannerSave({
              param
            }).then(res => {
              this.subLoading = false
              if (res.errorCode === '000000') {
                this.$message.success('提交成功')
                this.$router.replace(`/options/homePageList?renovate=1`)
              }
            }).catch(err => {
              console.log(err)
            })
          }
        } else {
          console.log('error submit!!')
          return false
        }
      })
    }
  }
}
</script>

<style lang="scss" scoped>
@import "@/styles/variables.scss";

.device-uploader {
  width: 80px;
  height: 80px;
  display: flex;
  align-items: center;
  justify-content: center;
  background-color: #fff;
  cursor: pointer;
  border: 1px dashed #ccc;
  border-radius: 8px;
  transition: all 0.3s;
  &:hover {
    border-color: $menuActive;
    .uploader-icon {
      color: $menuActive;
    }
  }
  ::v-deep .el-upload {
    width: 100%;
    height: 100%;
    display: flex;
    align-items: center;
    justify-content: center;
    position: relative;
    .file {
      width: 100%;
      height: 100%;
      position: absolute;
      top: 0;
      left: 0;
      background-size: contain;
      background-position: center;
      background-repeat: no-repeat;
      border-radius: 8px;
      display: flex;
      align-items: center;
      justify-content: center;
      .delete {
        background-color: rgba(0, 0, 0, 0.5);
        position: absolute;
        width: 100%;
        height: 100%;
        top: 0;
        left: 0;
        display: none;
        align-items: center;
        justify-content: center;
        .icon {
          color: #fff;
        }
      }
      &:hover {
        .delete {
          display: flex;
        }
      }
    }
  }
  .uploader-icon {
    color: #aaaaaa;
    font-size: 22px;
    transition: all 0.3s;
  }
}
.line-style {
  margin-bottom: 20px;
}
.device-uploaders {
  ::v-deep .el-upload-list__item {
    width: 80px;
    height: 80px;
  }
  ::v-deep .el-upload {
    width: 80px;
    height: 80px;
    line-height: 80px;
  }
}
</style>
